package com.kushe.dao;

import com.kushe.config.Config;
import com.kushe.entity.Group;
import com.kushe.util.core.DbUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;


import java.util.List;

/**
 * Created by WSDevotion on 2015/5/2.
 */
public class GroupDao {
    public static Group get(int id) {
        return DbUtils.getNutzDao().fetch(Group.class, id);
    }

    public static List<Group> getGroupByUser_id(int user_id){
        return DbUtils.getNutzDao().query(Group.class, Cnd.where("creater_id", "=", user_id));
    }

    public static Group getGroupByName(String name){
        return DbUtils.getNutzDao().fetch(Group.class, name);
    }

    public static Group addGroup(Group group) {
        Dao dao = DbUtils.getNutzDao();
        Group groups = dao.fetch(Group.class, group.getName());
        if (groups == null) {
            dao.insert(group);
            return group;
        } else
            return null;
    }


    public static QueryResult getByModule(int pageNumber, int type) {
        Dao dao = DbUtils.getNutzDao();
        Pager pager = dao.createPager(pageNumber, Config.PAGE_SIZE);
        List<Group> list = null;
        if(type==0) {
            list = dao.query(Group.class, null, pager);
        }else{
            list = dao.query(Group.class, Cnd.where("type", "=", type), pager);
        }
        pager.setRecordCount(dao.count(Group.class));
        return new QueryResult(list, pager);
    }

    public static List<Group> getBytype(int type) {
        Dao dao = DbUtils.getNutzDao();
        List<Group> list = dao.query(Group.class, Cnd.where("type", "=", type));

        return list;
    }


    public static QueryResult listByHot(int pageNumber, int type) {
        Dao dao = DbUtils.getNutzDao();
        Pager pager = dao.createPager(pageNumber, Config.PAGE_SIZE);
        List<Group> list = null;
        if(type==0) {
            Criteria cri = Cnd.cri();
            cri.getOrderBy().desc("num");
            list = dao.query(Group.class, cri, pager);
            pager.setRecordCount(dao.count(Group.class));
        }else{
            Criteria cri = Cnd.cri();
            cri.where().andEquals("type", type);
            cri.getOrderBy().desc("num");
            list = dao.query(Group.class, cri, pager);
            pager.setRecordCount(dao.count(Group.class, Cnd.where("type", "=", type)));
        }

        return new QueryResult(list, pager);
    }


    public static void updateGroup(Group group){
        Dao dao = DbUtils.getNutzDao();
        dao.update(group);
    }

}
